package com.vcom.deploy.cmd;

import org.noear.solon.aspect.annotation.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Service
public class CmdService {

    public String executeCmd(String cmd) {
        Process process = null;
        InputStream inputStream = null;
        InputStream errorStream = null;
        BufferedReader reader = null;
        try {
            String[] params = cmd.split(" ");
            ProcessBuilder pb = new ProcessBuilder(params);
            process = pb.start();
            int exitValue = process.waitFor();
            // 当返回值为0时表示执行成功
            if (0 != exitValue) {
                System.out.println("call shell failed. error code is :" + exitValue);
            }
            inputStream = process.getInputStream();
            errorStream = process.getErrorStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder stringBuilder = new StringBuilder(256);
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            reader = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8));
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            return stringBuilder.toString();
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
